//
//  HomeViewController.m
//  FbeeAPP
//
//  Created by dev-m on 2018/2/28.
//  Copyright © 2018年 mohao. All rights reserved.
//

#import "HomeViewController.h"
#import "BeeGroupListCell.h"
#import "BeeGroupListObj.h"
#import "UIScrollView+BCYRefresh.h"

@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>
{
    UIImageView *shadowBg;
    
    NSMutableArray *myBGArray;
    NSMutableArray *reBGArray;
    
    BOOL myExtend;
    BOOL reExtend;
    
    UITableView *mainTable;
    UIView *header;
    
    UIView *myFooterView;
    UIView *reFooterView;
    
    UIButton *walletBind;
}

@end

@implementation HomeViewController

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)viewDidAppear:(BOOL)animated
{
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

-(void)viewDidDisappear:(BOOL)animated
{
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

-(void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_ShowTabbar object:nil];
    [self showAddWalletInfo];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_HiddeTabbar object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titleLabel.text = @"Fbee";
    self.largeTitle.hidden = YES;

    myBGArray = [[NSMutableArray alloc] init];
    reBGArray = [[NSMutableArray alloc] init];
    
    //加入圈子成功刷新首页
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:Notification_JoinBeeGroupSuccess object:nil];
    //退出圈子成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:Notification_QuitBeeGroupSuccess object:nil];
    //登录成功刷新首页
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:Notification_LoginSuccess object:nil];
    //退出登录刷新首页
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:Notification_LoginOut object:nil];
    
    [self buildView];
    [self hiddeBack];
    [self bringTitleToFront];
    [self getHomeData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)buildView
{
    header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, 50)];
    
    UILabel * title = [UILabel makeLabel:^(TTLabelExtend *make) {
        make.setFrame(CGRectMake(16, 0, IPHONEWIDTH, 50));
        make.addText(@"Fbee");
        make.addFont([UIFont boldSystemFontOfSize:34.0f]).addTextColor(FBEE_COLOR_LARGETITLE);
        [header addSubview:make];
    }];
    
    mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, IPHONEHEIGHT) style:UITableViewStyleGrouped];
    mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    mainTable.alwaysBounceVertical = YES;
    mainTable.backgroundColor = [UIColor clearColor];
    mainTable.delegate = self;
    mainTable.dataSource = self;
    mainTable.showsVerticalScrollIndicator = NO;
    mainTable.tableHeaderView =header;
    [mainTable setContentInset:UIEdgeInsetsMake(NavBarHeight, 0, TabbarHeight, 0)];
    [self.view addSubview:mainTable];
    [mainTable addSubview:shadowBg];

    @weakify(self)
    [mainTable addHeaderByRefreshHandler:^{
        @strongify(self)
        [self getHomeData];
    }];
    
    
    for (int i = 0; i<3; i++) {
        BeeGroupListObj *obj = [BeeGroupListObj new];
        [myBGArray addObject:obj];
    }

    for (int i = 0; i<3; i++) {
        BeeGroupListObj *obj = [BeeGroupListObj new];
        [reBGArray addObject:obj];
    }
    
    //阴影
    shadowBg = [[UIImageView alloc] initWithFrame:CGRectZero];
    UIImage *img = [UIImage imageNamed:@"home_shadow"];
    img = [img resizableImageWithCapInsets:UIEdgeInsetsMake(80, 10, 80, 10) resizingMode:UIImageResizingModeStretch];
    shadowBg.image = img;
    shadowBg.frame = CGRectZero;
    shadowBg.top = header.height + 43;
    [self reSetShadowFrame];
    
}

#pragma mark - TableView Section

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (myBGArray.count == 0) {
        return 1;
    }
    
    return 2;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 1)
    {
        return 56;
    }
    
    return 53;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0 && 1 < myBGArray.count && myBGArray.count <= 3)
        return 0.1;
    
    return 44;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    NSString *titleStr;
    
    if (myBGArray.count == 0) {
        titleStr = NSLocalizedString(@"bGroupReGroup",nil);
    }
    else
    {
        titleStr = section == 0 ? NSLocalizedString(@"bGroupMyGroup",nil):NSLocalizedString(@"bGroupReGroup",nil);
    }
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, 53)];
    UILabel *title = [UILabel makeLabel:^(TTLabelExtend *make) {
        make.setFrame(CGRectMake(18, 23, IPHONEWIDTH - 18, 15));
        make.addText(titleStr);
        make.addFont([UIFont systemFontOfSize:14.0f]).addTextColor(FBEE_COLOR_THEME);
        [view addSubview:make];
    }];
    
    if (section == 1) {
        title.top = 32;
    }
    
    return view;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    //我的模块
    if (section == 0 && myBGArray.count > 3) {
        
        if (!myFooterView) {
            myFooterView = [self getFootView];
            
            @weakify(mainTable)
            @weakify(self)
            @weakify(myFooterView)
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id sender) {
                myExtend = !myExtend;
                
                @strongify(myFooterView)
                UILabel *title = [myFooterView viewWithTag:111];
                if (myExtend) {
                    title.text = @"收起查看";
                }
                else
                {
                    title.text = NSLocalizedString(@"mLoadAll",nil);
                }
                
                @strongify(mainTable)
                [mainTable reloadData];
                @strongify(self)
                [self reSetShadowFrame];
                [self reSetEmptyView];
                
                if (mainTable.contentSize.height <= IPHONEHEIGHT) {
                    
                    mainTable.tableHeaderView.alpha = 1;
                    self.navigationView.alpha = 0;
                }
            }];
            [myFooterView addGestureRecognizer:tap];
            
        }
        
        return myFooterView;
    }
    
    //推荐模块
    if ((reBGArray.count > 10 && section == 1) || (reBGArray.count > 10 && myBGArray.count == 0)) {
        
        if (!reFooterView) {
            
            reFooterView = [self getFootView];
            
            @weakify(mainTable)
            @weakify(self)
            @weakify(reFooterView)
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id sender) {
                reExtend = !reExtend;
                
                @strongify(reFooterView)
                UILabel *title = [reFooterView viewWithTag:111];
                if (reExtend) {
                    title.text = @"收起查看";
                }
                else
                {
                    title.text = NSLocalizedString(@"mLoadAll",nil);
                }
                
                @strongify(mainTable)
                [mainTable reloadData];
                [self reSetEmptyView];
                
                if (mainTable.contentSize.height <= IPHONEHEIGHT) {
                    mainTable.tableHeaderView.alpha = 1;
                    self.navigationView.alpha = 0;
                }
            }];
            [reFooterView addGestureRecognizer:tap];
        }
        
        return reFooterView;
        
    }
    
    return nil;
}

-(UIView *)getFootView
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, 44)];
    UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, 30)];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = NSLocalizedString(@"mLoadAll",nil);
    title.textColor =UIColorFromRGB(0x9b9b9b);
    title.font = [UIFont systemFontOfSize:14.0f];
    title.tag = 111;
    [view addSubview:title];
    
    return view;
}

#pragma mark - TableView Cell

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (myBGArray.count != 0)
    {
        //我的圈子
        if (section == 0) {
            NSUInteger min = myBGArray.count > 3 ? 3 : myBGArray.count;
            return myExtend ? myBGArray.count : min;
        }
        
        //推荐圈子
        if (section == 1) {
            NSUInteger min = reBGArray.count > 10 ? 10 : reBGArray.count;
            return reExtend ? reBGArray.count : min;
        }
    }
    

    NSUInteger min = reBGArray.count > 10 ? 10 : reBGArray.count;
    return reExtend ? reBGArray.count : min;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return BEELISTCELLHEIGHT;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellId = @"RECELLID";
    BeeGroupListCellType type = ReBeegroupType;
    
    BeeGroupListObj *obj = nil;
    

    if (indexPath.section == 0 && myBGArray.count > 0) {
        cellId = @"MYCELLID";
        type = MyBeegroupType;
    }
    
    if (type == MyBeegroupType) {
        obj = [myBGArray objectAtIndex:indexPath.row];
    }
    if (type == ReBeegroupType) {
        obj = [reBGArray objectAtIndex:indexPath.row];
    }
    
    
    BeeGroupListCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (!cell) {
        cell = [[BeeGroupListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId type:type];
    }
    
    cell.dataObj = obj;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    BeeGroupListObj *obj;
    
    if (indexPath.section == 0 && myBGArray.count > 0) {
        obj = [myBGArray objectAtIndex:indexPath.row];
    }
    else
    {
        obj = [reBGArray objectAtIndex:indexPath.row];
    }
    
    
    if (![NSString isEmptyString:obj.groupId]) {
        [[JumpManager sharedManager] jumpToBeeGroup:obj];
    }
    
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    [self shadowLowSubview];
}

-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self shadowLowSubview];
}

#pragma - mark scrollView

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //导航渐变
    if (scrollView.contentSize.height > IPHONEHEIGHT && mainTable.top >= 0) {
        
        float alphaY = scrollView.contentOffset.y;
        
        float alpha = alphaY / (scrollView.bounds.size.height/5.0f);
        float alphaH = 1 - alpha*2;
        
        alpha = alpha<0?0:alpha;
        alpha = alpha>1?1:alpha;
        alphaH = alphaH<0?0:alphaH;
        alphaH = alphaH>1?1:alphaH;
        
        
        [self.navigationView setAlpha:alpha];
        [header setAlpha:alphaH];
        [self.view bringSubviewToFront:self.navigationView];
    }
}

#pragma - mark Shadow

-(void)shadowLowSubview
{
    if (myBGArray.count==0) {
        shadowBg.hidden = YES;
        return;
    }
    shadowBg.hidden = NO;
    [mainTable insertSubview:shadowBg atIndex:0];
}

-(void)reSetShadowFrame
{
    if (myBGArray.count==0) {
        return;
    }
    
    NSUInteger min = myBGArray.count > 3 ? 3 : myBGArray.count;
    min = myExtend ? myBGArray.count : min;
    shadowBg.left = 0;
    shadowBg.width = IPHONEWIDTH;
    float footer = (myBGArray.count <= 3) ? 0.1 : 44;
    // 中间区域  尾  阴影
    shadowBg.height = 10 + min*BEELISTCELLHEIGHT + footer + 53;
}

-(void)reSetEmptyView
{
    UIView * emptyView = [mainTable viewWithTag:0x5f3a];
    
    if (emptyView) {
        emptyView.top = mainTable.contentSize.height;
        [mainTable setContentSize:CGSizeMake(0, emptyView.bottom + TabbarHeight)];
    }

}

-(void)showAddWalletInfo
{
    if ([UserInfoManager sharedManager].isLogin && ![UserInfoManager sharedManager].haveWallet) {
        
        if (!walletBind) {
            walletBind = [UIButton makeButton:^(TTButtonExtend *make) {
                make.addTitle(NSLocalizedString(@"homeWalletBind", nil)).addFont([UIFont systemFontOfSize:12.0f]).addTitleColor(COLOR_WHITE,UIControlStateNormal);
                make.addBackGoundColor(UIColorFromRGBA(0x584F60,0.5));
                make.addTarget(self,@selector(bindWallet));
                make.setFrame(CGRectMake(0, 0, 204, 25));
                make.layer.cornerRadius = 25/2;
                make.top = StatusHeight + 10;
                make.centerX = self.view.centerX;
                
            }];
        }
        [self.view addSubview:walletBind];
    }
    else
    {
        [walletBind removeFromSuperview];
    }
}

-(void)bindWallet
{
    [[JumpManager sharedManager] jumpToMyWalletAdd];
}


#pragma mark - getdata

-(void)getHomeData
{
    NSString *reurl = [NSString stringWithFormat:@"%@?pageNum=1&pageSize=100",RecommendBeeGroup_URL];
    NSString *myeurl = [NSString stringWithFormat:@"%@?pageNum=1&pageSize=100",MyBeeGroup_URL];

    if ([UserInfoManager sharedManager].isLogin) {
        
        reurl = [NSString stringWithFormat:@"%@&uid=%@",reurl,[UserInfoManager sharedManager].userId];
        myeurl = [NSString stringWithFormat:@"%@&uid=%@",myeurl,[UserInfoManager sharedManager].userId];
        
    }
    
    [self get:myeurl code:MyBeeGroup_URL_Code];
    [self get:reurl code:RecommendBeeGroup_URL_Code];


}

#pragma mark - requst

-(void)requestSuccess:(id)data code:(NSInteger)code
{
    
    if (code == RecommendBeeGroup_URL_Code) {
        
        [reBGArray removeAllObjects];
        
        [EmptyViewHelper removeEmptyFromView:mainTable];
        
        NSArray *dataArray = SafeGetArrayValue([data objectForKey:@"beeGroupList"]);

        //空页面
        if (dataArray.count == 0) {
            UIView *emptyView = [EmptyViewHelper showEmptyOnView:mainTable imageName:@"common_empty" text:NSLocalizedString(@"textEmptyHome", nil)];
            emptyView.height = 220;
        }
        
        for (NSDictionary *dict in dataArray) {
            BeeGroupListObj *obj = [[BeeGroupListObj alloc] init];
            [obj setObjByData:dict];
            [reBGArray addObject:obj];
        }
        [mainTable reloadData];
        [self reSetEmptyView];
        
    }
    
    if (code == MyBeeGroup_URL_Code) {
        
        [myBGArray removeAllObjects];
        
        NSArray *dataArray = SafeGetArrayValue([data objectForKey:@"beeGroupList"]);
        
        for (NSDictionary *dict in dataArray) {
            BeeGroupListObj *obj = [[BeeGroupListObj alloc] init];
            [obj setObjByData:dict];
            [myBGArray addObject:obj];
        }
        [mainTable reloadData];
        [self reSetShadowFrame];
        [self reSetEmptyView];
    }
    
    [mainTable endRefreshing];
    
}

-(void)requestLogicError:(id)data code:(NSInteger)code
{
    [super requestLogicError:data code:code];
    
    [mainTable endRefreshing];
}

-(void)requestFailure:(NSError *)error code:(NSInteger)code
{
    [mainTable endRefreshing];
}

#pragma mark - refresh Home

-(void)refreshData
{
    [self getHomeData];
}

@end
